package com.broker.starter.config;

import com.broker.starter.exception.MinIOException;
import com.broker.starter.service.MinIOService;
import com.broker.starter.service.impl.MinIOServiceImpl;
import io.minio.MinioClient;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Objects;

/**
 * MinIO配置类
 */
@Configuration
@EnableConfigurationProperties(MinIOPropertyConfig.class)
public class MinIOStarterAutoConfiguration {

    @Bean
    public MinioClient minioClient(MinIOPropertyConfig minIOConfig){
        checkConfig(minIOConfig);

        MinioClient minioClient = MinioClient.builder()
            .endpoint(minIOConfig.getEndpoint())
            .credentials(minIOConfig.getAccessKey(), minIOConfig.getSecretKey())
            .build();

        return minioClient;
    }

    private void checkConfig(MinIOPropertyConfig minIOConfig) {
        if (Objects.isNull(minIOConfig)){
            throw new MinIOException("minIOConfig can't be empty.");
        }
        if (StringUtils.isEmpty(minIOConfig.getEndpoint())){
            throw new MinIOException("Endpoint can't be empty.");
        }
        if (StringUtils.isEmpty(minIOConfig.getAccessKey())){
            throw new MinIOException("AccessKey can't be empty.");
        }
        if (StringUtils.isEmpty(minIOConfig.getSecretKey())){
            throw new MinIOException("SecretKey can't be empty.");
        }
    }

    @Bean
    public MinIOService minIOService(){
        return new MinIOServiceImpl();
    }
}
